Page({
  data: {
    totalMembers: '',
    groupCount: '',
    groupNames: [],
    recentPlans: []
  },

  // 添加格式化时间的辅助函数
  formatDate(date) {
    const year = date.getFullYear()
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    const hours = date.getHours().toString().padStart(2, '0')
    const minutes = date.getMinutes().toString().padStart(2, '0')
    const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
    
    return `${year}-${month}-${day} ${hours}:${minutes} ${weekdays[date.getDay()]}`
  },

  onLoad() {
    // 设置导航栏
    wx.setNavigationBarTitle({
      title: '创建分组'
    })
    
    // 检查登录状态
    const app = getApp()
    if (!app.globalData.userInfo) {
      wx.showModal({
        title: '提示',
        content: '请先返回首页完成登录',
        showCancel: false,
        success: () => {
          wx.navigateBack()
        }
      })
      return
    }
    
    // 获取最近的分组计划，并处理已有记录的时间格式
    const recentPlans = (app.globalData.plans || []).map(plan => {
      try {
        // 直接使用原始时间字符串创建Date对象
        const date = new Date(plan.createTime)
        // 检查是否是有效的日期
        if (isNaN(date.getTime())) {
          console.warn('Invalid date:', plan.createTime)
          return plan // 如果日期无效，保持原样
        }
        plan.createTime = this.formatDate(date)
      } catch (err) {
        console.error('时间格式化失败:', err)
      }
      return plan
    })
    
    this.setData({
      recentPlans
    })

    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#3498db'
    });
  },

  onHistoryItemTap(e) {
    const index = e.currentTarget.dataset.index
    const plan = this.data.recentPlans[index]
    
    // 设置为当前计划
    getApp().globalData.currentPlan = plan
    
    // 跳转到结果页面
    wx.navigateTo({
      url: `/pages/result/result?planId=${plan.id}`
    })
  },

  onTotalMembersChange(e) {
    this.setData({
      totalMembers: e.detail.value
    })
  },

  onGroupCountChange(e) {
    const count = parseInt(e.detail.value) || 0
    // 当分组数改变时，自动生成默认组名
    const groupNames = Array(count).fill('').map((_, index) => `${index + 1}组`)
    
    this.setData({
      groupCount: count,
      groupNames
    })
  },

  onGroupNameChange(e) {
    const index = e.currentTarget.dataset.index
    const value = e.detail.value
    const groupNames = [...this.data.groupNames]
    
    // 如果用户输入了名称，就使用用户输入的，否则保持默认的"X组"
    groupNames[index] = value || `${index + 1}组`
    
    this.setData({
      groupNames
    })
  },

  createPlan() {
    const app = getApp()
    
    // 检查是否已登录
    if (!app.globalData.userInfo) {
      wx.showToast({
        title: '请先返回首页登录',
        icon: 'none',
        duration: 2000
      })
      return
    }

    if (!this.data.totalMembers) {
      wx.showToast({
        title: '请输入总人数',
        icon: 'none'
      })
      return
    }
    if (!this.data.groupCount) {
      wx.showToast({
        title: '请输入分组数',
        icon: 'none'
      })
      return
    }

    const now = new Date()
    
    const plan = {
      id: app.generateId(),
      totalMembers: parseInt(this.data.totalMembers),
      groupCount: parseInt(this.data.groupCount),
      groupNames: this.data.groupNames,
      creator: app.globalData.userInfo.nickName,
      createTime: this.formatDate(now),
      status: 'waiting',
      members: []
    }

    // 保存到全局数据
    app.globalData.currentPlan = plan
    app.globalData.plans = [plan, ...app.globalData.plans]
    app.savePlans()

    // 跳转到结果页
    wx.navigateTo({
      url: `/pages/result/result?planId=${plan.id}`
    })
  },

  goBack() {
    wx.navigateBack()
  },

  handleMovableChange(e) {
    const { index } = e.currentTarget.dataset
    const { x } = e.detail
    
    // 更新滑动状态
    const recentPlans = [...this.data.recentPlans]
    recentPlans[index].xMove = x
    this.setData({ recentPlans })
  },

  handleTouchEnd(e) {
    const { index } = e.currentTarget.dataset
    const { xMove = 0 } = this.data.recentPlans[index]
    
    // 判断是否显示删除按钮，调整阈值
    const updateX = xMove <= -50 ? -100 : 0
    
    const recentPlans = [...this.data.recentPlans]
    recentPlans[index].xMove = updateX
    this.setData({ recentPlans })
  },

  handleDelete(e) {
    const { index } = e.currentTarget.dataset
    
    wx.showModal({
      title: '确认删除',
      content: '是否删除此记录？',
      success: (res) => {
        if (res.confirm) {
          // 从数组中移除
          const recentPlans = [...this.data.recentPlans]
          recentPlans.splice(index, 1)
          
          // 更新全局数据
          const app = getApp()
          app.globalData.plans = recentPlans
          app.savePlans()
          
          // 更新页面数据
          this.setData({ recentPlans })
          
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          })
        }
      }
    })
  }
}) 